//
//  NetworkTools.swift
//  AFNetworkingSwiftDemo
//
//  Created by Quentin Zang on 2020/3/14.
//  Copyright © 2020 臧乾坤. All rights reserved.
//

import UIKit
import AFNetworking

///  请求方法枚举
enum HMRequsetMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {

    // MARK: - 应用程序信息
    private let appKey = "3816164474"
    private let appSecret = "fc74026b7bb997543a5b6dcc4758e601"
    private let redirectUrl = "http://www.baidu.com"
    
    // 类似于 OC 的 typeDefine
    typealias HMRequsetCallBack = (_ result: Any, _ error: Error?)-> ()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
       return tools
    }()
}

// MARK: - 封装 OAuth 网络方法
extension NetworkTools {
    
    /// OAuth 授权 URL
    /// - see: [https://open.weibo.com/wiki/Oauth2/authorize](https://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: URL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(appSecret)"
        return URL(string: urlString)!
    }
    
    
    /// 加载授权
    /// - Parameter code: 授权token
    func loadAccessToken(code: String, finished:@escaping HMRequsetCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appKey,
                      "client_secret": appSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": redirectUrl]
        request(method: .POST, URLString: urlString, parameters: params, finished: finished)
    }
    
}


// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    /// 网络请求
    /// - Parameters:
    ///   - method: get/post
    ///   - URLString: 网址
    ///   - parameters: 参数字典
    ///   - finished: 完成回调
    func request(method: HMRequsetMethod, URLString: String, parameters: [String: Any]?, finished:@escaping (_ result: Any?, _ error: Error?) -> ()) {
        
        // 定义成功回调
        let success = { (task: URLSessionTask, result: Any) -> Void in
            finished(result, nil)
            
        }
        
        // 定义失败回调
        let failure = { (task: URLSessionTask, error: Error) -> Void in
            print(error)
            finished(nil,error as NSError)
        }
        
        if method == HMRequsetMethod.GET {
            get(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, success: success, failure: failure)
        }
        
    }
    
}

// MARK: - 微博数据相关方法
//extension NetworkTools {
//    func loadStatus() {
//        // 1.获取 token 字典
//        guard var params = tokenDict  else {
//            <#statements#>
//        }
//    }
//}
